
# Store File (Store & Upload)
# Author: Rishav Jain

# importing variables from other project files
from profile import profile
import variables
from upload import uploadReadings
from post import postReadings

import threading
import time


PostTask = threading.Thread(target = postReadings, args=())

def SampleTask():
    PostTask.start()

    # Light.APDS_init()

    prevTime = time.time()

    while True:
            nowTime = time.time()

            if nowTime-prevTime > 1:
                    prevTime = nowTime
                    
                    if variables.alarmCount == 0:
                            variables.lockTimestamp.acquire()
                            variables.timestamp = nowTime
                            variables.lockTimestamp.release()
                        
                    if variables.alarmCount % profile.SamplingPeriod == 0:
                            variables.alarmRead = 1
                            variables.alarmRead = 0
                            print('\nSampling - ' + time.asctime())
                            
                            if variables.alarmCount%2 == 0:
                                    variables.TempReadings += (0.0,)
                                    variables.LightReadings += (0.0,)
                                    variables.PirReadings += (0,)
                                    
                            else:
                                    variables.TempReadings += (1.0,)
                                    variables.LightReadings += (1.0,)
                                    variables.PirReadings += (1,)		   

                            
                            '''
                            variables.lockTemp.acquire()	
                            variables.TempReadings += (Temp.read_temp(),)
                            variables.lockTemp.release()

                            variables.lockLight.acquire()
                            Light.APDS_init()
                            variables.LightReadings += (Light.APDS_read(),)
                            variables.lockLight.release()

                            variables.lockPir.acquire()
                            variables.PirReadings += (PIR.PIR_Read(),)
                            variables.lockPir.release()
                            '''
    ##			print(variables.TempReadings)
    ##			print(variables.LightReadings)
    ##			print(variables.PirReadings)
                        
                    variables.alarmCount += 1
                    if variables.alarmCount % profile.PublishPeriod == 0:
                        variables.alarmUpload = 1
                        variables.alarmCount = 0
                        time.sleep(0.0001)
                    
                    #time.sleep(1)
